<template>
  <div class="waterfall-wrapper">
    <div class="waterfall-container" ref="containerRef">
      <!-- 瀑布流列 -->
      <div class="waterfall-column" v-for="(column, index) in columns" :key="index" :style="{ width: columnWidth }">
        <div
          class="waterfall-item"
          v-for="item in column"
          :key="item.id"
          :data-id="item.id"
          :style="{ marginBottom: gutter + 'px' }"
        >
          <slot name="item" :item="item">
            <!-- 默认内容 -->
            <div class="default-item">
              <img
                v-if="item.image"
                :src="item.image"
                :alt="item.title || '图片'"
                @load="handleImageLoad"
                loading="lazy"
              />
              <h3 v-if="item.title">{{ item.title }}</h3>
              <p v-if="item.desc">{{ item.desc }}</p>
            </div>
          </slot>
        </div>
      </div>
    </div>

    <!-- 底部固定加载区域 -->
    <div class="waterfall-footer">
      <div class="load-more" v-if="hasMore && !loading">
        <a-button type="primary" @click="loadMore" block>加载更多</a-button>
      </div>

      <div class="loading-state" v-if="loading">
        <a-spin tip="加载中..." />
      </div>

      <div class="no-more" v-if="!hasMore && items.length > 0">
        <a-divider>没有更多了</a-divider>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onBeforeUnmount, watch } from "vue";
import { debounce } from "lodash-es";

const props = defineProps({
  // 数据源
  items: {
    type: Array,
    required: true,
    default: () => [],
  },
  // 列数
  columnCount: {
    type: Number,
    default: 4,
  },
  // 列间距
  gutter: {
    type: Number,
    default: 16,
  },
  // 是否还有更多数据
  hasMore: {
    type: Boolean,
    default: false,
  },
  // 是否自动计算高度（用于动态高度内容）
  autoHeight: {
    type: Boolean,
    default: false,
  },
  // 是否启用响应式布局
  responsive: {
    type: Boolean,
    default: true,
  },
  // 响应式断点配置
  breakpoints: {
    type: Object,
    default: () => ({
      1400: 4, // 屏幕宽度 >= X 时显示 X列
      1000: 3,
      600: 2,
      0: 1,
    }),
  },
});

const emit = defineEmits(["load-more"]);

const containerRef = ref(null);
const loading = ref(false);
const currentColumnCount = ref(props.columnCount);
const itemHeights = ref({}); // 存储项目高度（用于autoHeight模式）

// 计算列宽
const columnWidth = computed(() => {
  const totalGutter = (currentColumnCount.value - 1) * props.gutter;
  return `calc((100% - ${totalGutter}px) / ${currentColumnCount.value})`;
});

// 根据当前列数分配项目到各列
const columns = computed(() => {
  const cols = Array.from({ length: currentColumnCount.value }, () => []);

  if (props.autoHeight) {
    // 动态高度模式 - 将项目放入当前最短的列
    const colHeights = Array(currentColumnCount.value).fill(0);

    props.items.forEach((item) => {
      // 找到当前最短的列
      const shortestColIndex = colHeights.indexOf(Math.min(...colHeights));
      cols[shortestColIndex].push(item);

      // 更新列高度（加上项目高度和间距）
      const itemHeight = itemHeights.value[item.id] || 0;
      colHeights[shortestColIndex] += itemHeight + props.gutter;
    });
  } else {
    // 固定高度模式 - 简单按顺序分配
    props.items.forEach((item, index) => {
      const colIndex = index % currentColumnCount.value;
      cols[colIndex].push(item);
    });
  }

  return cols;
});

// 处理响应式布局
const handleResponsive = () => {
  if (!props.responsive) return;

  const width = window.innerWidth;
  let newColumnCount = props.columnCount;

  // 根据断点确定列数
  for (const [breakpoint, count] of Object.entries(props.breakpoints)) {
    if (width >= parseInt(breakpoint)) {
      newColumnCount = count;
    } else {
      break;
    }
  }

  if (newColumnCount !== currentColumnCount.value) {
    currentColumnCount.value = newColumnCount;
  }
};

// 图片加载完成时记录高度（用于autoHeight模式）
const handleImageLoad = (event) => {
  if (!props.autoHeight) return;

  const itemElement = event.target.closest(".waterfall-item");
  if (!itemElement) return;

  const itemId = itemElement.dataset.id;
  if (!itemId) return;

  // 记录项目高度
  itemHeights.value[itemId] = itemElement.offsetHeight;
};

// 加载更多数据
const loadMore = async () => {
  if (loading.value || !props.hasMore) return;

  loading.value = true;
  try {
    await emit("load-more");
  } finally {
    loading.value = false;
  }
};

// 初始化
onMounted(() => {
  handleResponsive();

  if (props.responsive) {
    window.addEventListener("resize", debounce(handleResponsive, 200));
  }
});

// 清理
onBeforeUnmount(() => {
  if (props.responsive) {
    window.removeEventListener("resize", debounce(handleResponsive, 200));
  }
});

// 监听items变化（用于autoHeight模式）
watch(
  () => props.items,
  () => {
    if (!props.autoHeight) return;

    // 下一帧重新计算高度
    requestAnimationFrame(() => {
      const itemElements = containerRef.value?.querySelectorAll(".waterfall-item") || [];
      itemElements.forEach((el) => {
        const id = el.dataset.id;
        if (id) {
          itemHeights.value[id] = el.offsetHeight;
        }
      });
    });
  },
  { deep: true }
);
</script>

<style scoped lang="less">
.waterfall-wrapper {
  display: flex;
  flex-direction: column;
  height: 100%;
  position: relative;
}

.waterfall-container {
  display: flex;
  justify-content: space-between;
  width: 100%;
  margin: 0 auto;
  padding: 0;
  box-sizing: border-box;
  flex: 1;
  overflow-y: auto;

  .waterfall-column {
    display: flex;
    flex-direction: column;
    box-sizing: border-box;
  }

  .waterfall-item {
    width: 100%;
    box-sizing: border-box;
    break-inside: avoid;

    .default-item {
      background: #fff;
      border-radius: 4px;
      overflow: hidden;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
      transition: transform 0.3s, box-shadow 0.3s;

      &:hover {
        transform: translateY(-4px);
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
      }

      img {
        width: 100%;
        height: auto;
        display: block;
      }

      h3 {
        margin: 12px;
        font-size: 16px;
        color: #333;
      }

      p {
        margin: 0 12px 12px;
        font-size: 14px;
        color: #666;
      }
    }
  }
}

.waterfall-footer {
  padding: 16px 0;
  background: #fff;
  border-top: 1px solid #f0f0f0;
  position: sticky;
  bottom: 0;
  z-index: 1;

  .load-more {
    max-width: 300px;
    margin: 0 auto;
  }

  .loading-state {
    display: flex;
    justify-content: center;
    padding: 8px 0;
  }

  .no-more {
    text-align: center;
    color: #999;
    font-size: 14px;
  }
}

/* 响应式调整 */
@media (max-width: 768px) {
  .waterfall-container {
    flex-direction: column;

    .waterfall-column {
      width: 100% !important;
    }
  }

  .waterfall-footer {
    padding: 12px 16px;

    .load-more {
      max-width: 100%;
    }
  }
}
</style>
